// 店铺
const {auth} = require("../utils");
const router = require('koa-router')()
const Shops = require('../models/shops')
const Users = require('../models/users')
// 注册店铺
router.post('/',auth, async function (ctx, next) {
    let user = await Users.findById(ctx.state.user._id)
    console.log(user)
    if(user.shop){
        ctx.throw(208, '已经开通店铺了');
    }else {
        ctx.verifyParams({
            name: {type: "string", required: true},
            fmImg:{type: "string", required: true},
            address:{type:"object",required:true},
            category:{type: "array", required: true}
        })
        ctx.request.body.boss = ctx.state.user._id
        let shop = await Shops.create(ctx.request.body)
        await  Users.findByIdAndUpdate(ctx.state.user._id,{shop:shop._id})
        ctx.body = shop
    }
})

// 自己的店铺
router.get('/',  auth,async function (ctx, next) {
    let shop = await Shops.findOne({boss:ctx.state.user._id}).populate(['boss','goodsArr.goods'])
    if(!shop){
        ctx.throw(404, '店铺未开通')
    }
    ctx.body =shop
})

// 查看店铺
router.get('/li/:id',async function (ctx, next) {
    let shop = await Shops.findById(ctx.params.id).populate(['boss','goodsArr.goods'])
    if(!shop){
        ctx.throw(404, '店铺不存在')
    }
    ctx.body =shop
})

// 店铺列表
router.get('/lis',async function (ctx, next) {
    ctx.body = await Shops.find().populate('boss').populate(['boss','goodsArr.goods']).sort({'createdAt':-1})
})

// 修改店铺列表
router.put('/:id', auth,async function (ctx, next) {
    await Shops.findByIdAndUpdate(ctx.params.id,ctx.request.body)
    ctx.body = await Shops.findById(ctx.params.id).populate(['boss','goodsArr.goods']).sort({'createdAt':-1})
})

// 注销店铺
router.delete('/:id', auth, async function (ctx){
    let shop = await Shops.findByIdAndDelete(ctx.params.id)
    if(shop){
        await Users.findByIdAndUpdate(ctx.state.user._id,{$unset:{shop:ctx.params.id}})
        ctx.status = 204;
    }else {
        ctx.throw(404, '店铺不存在');
    }

})


module.exports = router
